﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Umbraco.Cms.Web.EmbeddedViewEngine;
using Umbraco.Cms.Web.Model.BackOffice.PropertyEditors;
using System.IO;
using System.Web;

namespace Filesystem.FilePicker
{
    [EmbeddedView("Filesystem.FilePicker.Views.FilePickerEditor.cshtml", "Filesystem.FilePicker")]
    public class FilePickerEditorModel : EditorModel<FilePickerPreValueModel>
    {
        public FilePickerEditorModel(FilePickerPreValueModel preValues)
            : base(preValues)
        {
            this.RootDir = preValues.RootDirectory;
            this.FileExt = preValues.FileExtension;
        }

        public string FileExt { get; private set; }

        public string RootDir { get; private set; }

        public string FilePath { get; set; }

        public string _value = "";

        public string Value 
        {
            get
            {
                return GetUrl();
            }
            set
            {
                _value = value;
            }
        }

        public override IDictionary<string, object> GetSerializedValue()
        {
            if (!Exists)
                FilePath = "";
            return base.GetSerializedValue();
        }

        public bool Exists
        {
            get
            {
                GetUrl();
                return File.Exists(HttpContext.Current.Server.MapPath(Value));
            }
            set
            {}
        }

        public override string ToString()
        {
            return Value;
        }

        private string GetUrl()
        {
            if (string.IsNullOrEmpty(FilePath))
                return "";
            if (string.IsNullOrEmpty(RootDir))
                RootDir = "/";
            if (!RootDir.EndsWith("/"))
                RootDir += "/";
            string Value = RootDir + FilePath;
            return Value;
        }

    }
}
